package com.duo.controller.admin;

import com.duo.dto.CategoryDTO;
import com.duo.dto.CategoryUpdateDTO;
import com.duo.entity.Category;
import com.duo.result.BaseResult;
import com.duo.service.CategoryService;
import com.duo.vo.CategoryVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Xrx
 * @Description:
 * @CreateTime: 2023/7/6 18:45
 */
@RestController
@RequestMapping("/admin/category")
@Slf4j
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类
     * @param categoryDTO
     * @return
     */
    @PostMapping("/save")
    public Object save(@RequestBody @Valid CategoryDTO categoryDTO) {
        categoryService.save(categoryDTO);
        return BaseResult.success("新建分类成功");
    }

    /**
     * 根据分类id删除分类
     */
    @DeleteMapping("/delete/{id}")
    public Object delete(@PathVariable("id") Long id) {
        log.info("删除分类：{}", id);
        categoryService.delete(id);
        return BaseResult.success("删除分类成功");
    }

    /**
     * 根据分类id修改分类
     */
    @PutMapping("/update")
    public Object update(@RequestBody @Valid CategoryUpdateDTO categoryDTO) {
        log.info("修改分类：{}", categoryDTO);
        categoryService.update(categoryDTO);
        return BaseResult.success("修改分类成功");
    }

    /**
     * 查询全部分类
     * @return
     */
    @PostMapping("/list")
    public Object list() {
        List<Category> list = categoryService.list();
        List<CategoryVO> categoryVOS = new ArrayList<>();
        list.forEach(category -> {
            CategoryVO categoryVO = new CategoryVO();
            BeanUtils.copyProperties(category, categoryVO);
            categoryVOS.add(categoryVO);
        });
        return BaseResult.success("类别分页查询成功", categoryVOS);
    }


}
